import LiuMove from "../components/Move.js";
let el = document.querySelector("[src='./size_horn.js']");
let elStr = el.getAttribute("tag") ? el.getAttribute("tag") : 'body';
customElements.define("liu-move", LiuMove);
let liuMove = document.createElement('liu-move');
document.querySelector(elStr).appendChild(liuMove);

const sizeHornEl = document.querySelector('.size-horn');
const headerEl = document.querySelector('.haoyong-header');
const todoNotesEl = document.querySelector('todo-notes');
const timeNotesEl = document.querySelector('time-notes');
const textNotesEl = document.querySelector('text-notes');
let x, y,_left = 0, _top = 0, _right = 0,rx = 0, s = 0.3, enterTime,leaveTime, aevent;
window.isfocus = false
let receive = {
  isReceive: null,
  type: null,
}
let bound = {
  width: document.documentElement.clientWidth,
  height: document.documentElement.clientHeight,
}
let bounds =  [];
let id = window.utools.getPrimaryDisplay().id;
let allDisplay = window.utools.getAllDisplays();
let index = allDisplay.findIndex(item=>item.id === id);
bounds = [...allDisplay.splice(index, 1), ...allDisplay];

bounds.forEach((item,index)=>{
  if(index === 0){
    _left = item.bounds.x;
    _top = item.bounds.y;
  }
  if(index === bounds.length - 1){
    _right = item.bounds.x + item.bounds.width;
    rx = item.bounds.x;
  }
});

if(window.ipcRenderer){
  window.ipcRenderer.on('getBounds', (event, res) => {
    bound = res;
  });
}

const focusHandle = (e) => {
  e.stopPropagation();
  window.isfocus = true;
}
window.blurHandle = (e) => {
  e.stopPropagation();
  window.isfocus = false;
  
  if(e.sourceCapabilities === null){
    initIsReceive(aevent);
    eceiveReceive({
      x: aevent.screenX - aevent.clientX,
      y: aevent.screenY - aevent.clientY,
      width: document.documentElement.clientWidth,
      height: document.documentElement.clientHeight
    });
  }
}

todoNotesEl.onfocus = focusHandle;
todoNotesEl.onblur = window.blurHandle;
textNotesEl.onfocus = focusHandle;
textNotesEl.onblur = window.blurHandle;
timeNotesEl.onfocus = focusHandle;
timeNotesEl.onblur = window.blurHandle;
const sendGetBounds = () => {
  if(window.ipcRenderer){
    window.ipcRenderer.sendTo( window.senderId ,'getBounds');
  }
}
let screenX = 0, screenY = 0, sizeDown = false;
sizeHornEl.addEventListener('mousedown', (e)=>{
  e.stopPropagation();
  window.ipcRenderer.sendTo( window.senderId ,'setResizable', true);
  if(e.button !== 0)return;
  bound = {
    width: document.documentElement.clientWidth,
    height: document.documentElement.clientHeight,
  }
  sizeDown = true;
  screenX = e.screenX;
  screenY = e.screenY;
  
});

document.addEventListener('mousemove', (e)=>{
  e.stopPropagation();
  if(sizeDown){
    let width = bound.width + (e.screenX - screenX);
    let height = bound.height + (e.screenY - screenY);
    ipcRenderer.sendTo(window.senderId, "setSize", {width, height});
  }
});

document.addEventListener('mouseup', (e)=>{
  e.stopPropagation();
  window.ipcRenderer.sendTo( window.senderId ,'setResizable', false);
  sizeDown = false;
});

let docDown = false, clientX = 0, clientY = 0,timeoutId, docWidth, docHeight;

// 拖动
document.addEventListener('mousedown', (e)=>{
  if(e.button !== 0)return;
  clearTimeout(timeoutId); 
  clientX = e.clientX;
  clientY = e.clientY;
  timeoutId = setTimeout(function(){
    docDown = true;
    clientX = e.clientX;
    clientY = e.clientY;
    docWidth = window.innerWidth;
    docHeight = window.innerHeight;
    document.documentElement.classList.add('long-press-animation');
  }, 400)
})
document.addEventListener('mousemove', (e)=>{
  if(docDown){
    let x = e.screenX - clientX;
    let y = e.screenY - clientY;
    ipcRenderer.sendTo(window.senderId, "setPosition", {x,y, width: docWidth, height: docHeight});
  }else{
    if(e.clientX !== clientX && e.clientY !== clientY){
      clearTimeout(timeoutId);
    }
    docDown = false;
    clientX = 0;
    clientY = 0;
  }
})
document.addEventListener('mouseup', (e)=>{
  setTimeout(()=>{
    clientX = 0;
    clientY = 0;
  },50)
  docDown = false;
  document.documentElement.classList.remove('long-press-animation')
  clearTimeout(timeoutId);
  if(window.sendSaveData){
    let data = window.getData();
    window.sendSaveData(data);
  }
})

document.addEventListener('mouseleave', (e)=>{
  e.stopPropagation();
  if(!docDown)return;
  clientX = 0;
  clientY = 0;
  docDown = false;
  document.documentElement.classList.remove('long-press-animation')
  clearTimeout(timeoutId);
})


// 头部拖动
let headDown = false, headClientX = 0, headClientY = 0, headWidth, headHeight;
headerEl.addEventListener('mousedown', (e)=>{
  e.stopPropagation();
  if(e.button !== 0)return;
  headDown = true;
  headClientX = e.clientX;
  headClientY = e.clientY;

  headWidth = window.innerWidth;
  headHeight = window.innerHeight;
  
});

document.addEventListener('mousemove', (e)=>{
  e.stopPropagation();
  if(headDown){
    let x = e.screenX - headClientX;
    let y = e.screenY - headClientY;
    ipcRenderer.sendTo(window.senderId, "setPosition", {x,y, width:headWidth, height: headHeight});
    if(receive.type === 'left'){
      window.renderTags();
    }
  }
});

document.addEventListener('mouseup', (e)=>{
  e.stopPropagation();
  headDown = false;
});



document.addEventListener('mouseleave', (e)=>{
  e.stopPropagation();
  aevent = e;
  headDown = false;
  clearTimeout(enterTime);

  initIsReceive(e);
  if(receive.isReceive === null && receive.type === null) return;
  leaveTime = setTimeout(()=>{
    eceiveReceive({
      x: e.screenX - e.clientX,
      y: e.screenY - e.clientY,
      width: document.documentElement.clientWidth,
      height: document.documentElement.clientHeight
    });
  }, 300)
});

document.addEventListener('mouseenter', (e)=>{
  e.stopPropagation();
  clearTimeout(leaveTime);
  initIsReceive(e);
  enterTime = setTimeout(()=>{
    eceiveExpand({
      x: e.screenX - e.clientX,
      y: e.screenY - e.clientY,
      width: document.documentElement.clientWidth,
      height: document.documentElement.clientHeight
    })
  }, 300)
});

const initIsReceive = (e) => {
  _top = utools.getDisplayNearestPoint({x: e.screenX, y: e.screenY}).bounds.y;
  let x = e.screenX - e.clientX;
  let y = e.screenY - e.clientY;
  let width = document.documentElement.clientWidth;
  let height = document.documentElement.clientHeight;
  
  if(width - (_left - x) < 80 ){
    receive = {
      isReceive: true,
      type: 'left'
    }
    return x;
  }else if((_left - x) > 1 ){
    receive = {
      isReceive: false,
      type: 'left'
    }
    return x;
  }

  if(height - (_top - y) < 10 ){
    receive = {
      isReceive: true,
      type: 'top'
    }
    return x;
  }else if( _top - y > 1){
    
    receive = {
      isReceive: false,
      type: 'top'
    }
    return x;
  }
  
  if(_right - x < 80){
    receive = {
      isReceive: true,
      type: 'right'
    }
    return x;
  }else if(_right - x < (width - 70)){
    receive = {
      isReceive: false,
      type: 'right'
    }
    return x;
  }

  receive = {
    isReceive: null,
    type: null
  }
}

let interval = (info, s) => {
  let total;
  
  let c =info.num / (60 * s);

  let type = info.type;
  let x = info.x;
  let y = info.y;
  let t = setInterval(()=>{
    if(type === 'left'){
      total = info.x - info.num;
      x = x - c;
      
      if(total - x > -5){
        x = total + 5;
        window.renderTags('right')
        clearInterval(t);
        receive = {
          isReceive: true,
          type: 'left'
        }
      }
    } else if (type === 'top') {
      total = info.y - info.num;
      y = y - c;
      if((total - y) > -5){
        y = total  + 5;
        clearInterval(t);
        receive = {
          isReceive: true,
          type: 'top'
        }
      }
    } else if (type === 'right') {
      total = info.x + info.num;
      x = x + c;
      
      if(total - x < 145){
        x = total - 145;
        clearInterval(t);
        receive = {
          isReceive: true,
          type: 'right'
        }
      }
    }
    ipcRenderer.sendTo(window.senderId, "setPosition", {x: parseInt(x),y: parseInt(y)});
    // receive.isReceive = true;
  }, 16.6)
}

const crossHidden = (bound) => {
  if(receive.isReceive)return;
  if(bound.y - 10 < _top){
    let beyond =  _top - bound.y;
    let remaining = bound.height - beyond;
    interval(
      {
        type: 'top',
        num: remaining,
        x: bound.x,
        y: bound.y
      }, s
    )
    return;
  }

  if(bound.x < _left){
    let beyond =  _left - bound.x;
    let remaining = (bound.width - 70) - beyond;
    interval(
      {
        type: 'left',
        num: remaining,
        x: bound.x,
        y: bound.y
      }, s
    )
    return;
  }
  
  if(bound.x + (bound.width - 70) > _right){
    let beyond = bound.x + (bound.width - 70) - _right;
    let remaining = bound.width - beyond;
    interval(
      {
        type: 'right',
        num: remaining,
        x: bound.x,
        y: bound.y
      }, s
    )
    return;
  }

}

const eceiveExpand = (bound)=>{
  if(!receive.isReceive)return;

  let c,x = bound.x,y = bound.y;

  let t = setInterval(()=>{
    switch (receive.type) {
      case 'top':{
        if(!c)c = (y - _top) / (60 * s);
        y -= c;
        if(y > _top - 5){
          y = _top - 5;
          clearInterval(t);
          receive = {
            isReceive: false,
            type: 'top'
          };
        }
        break;
      }
      case 'left':{
        if(!c){c = (x - _left) / (60 * s);}
        x -= c;
        if(x > -75){
          x = _left - 75;
          clearInterval(t);
          receive = {
            isReceive: false,
            type: 'left'
          };
        }
        break;
      }
      case 'right':{
        if(!c){
          c = (bound.width - (_right - x)) / (60 * s)
        }
        x -= c;
        if((bound.width - (_right - x)) < 75){
          x = _right - bound.width + 75;
          clearInterval(t);
          receive = {
            isReceive: false,
            type: 'right'
          };
        }
        break;
      }
      default:
        break;
    }
    ipcRenderer.sendTo(window.senderId, "setPosition", {x: parseInt(x),y: parseInt(y), width:bound.width, height: bound.height});
  }, 16.6)
 
}

const eceiveReceive = (bound) => {
  if(receive.isReceive === null || receive.isReceive || isfocus)return;

  let c,x = bound.x,y = bound.y;

  let t = setInterval(()=>{
    switch (receive.type) {
      case 'top':{
        if(!c)c = (bound.height - (_top - y)) / (60 * s);
        y -= c;
        if((bound.height - (_top - y)) < 5 ){
          y = _top - (bound.height - 3);
          clearInterval(t);
          receive = {
            isReceive: true,
            type: 'top'
          };
        }
        break;
      }
      case 'left':{
        if(!c){c = (bound.width - (_left - x)) / (60 * s);}
        x -= c;
        
        if((bound.width - (_top - x)) < 75){
          x = _left - (bound.width - 73);
          
          window.renderTags('right')
          clearInterval(t);
          receive = {
            isReceive: true,
            type: 'left'
          };
        }
        break;
      }
      case 'right':{
        if(!c){
          c =  (_right - x) / (60 * s)
        }
        x += c;
        if((_right - x) < 75){
          x = _right - 73;
          clearInterval(t);
          receive = {
            isReceive: true,
            type: 'right'
          };
        }
        break;
      }
      default:
        break;
    }
    ipcRenderer.sendTo(window.senderId, "setPosition", {x: parseInt(x),y: parseInt(y), width:bound.width, height: bound.height});
  }, 16.6)
}